<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\Front\Order;
use App\User;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::join('order_products', 'orders.id', '=', 'order_products.order_id')
                        ->join('products', 'order_products.product_id', '=', 'products.pro_code')
                        ->where('orders.user_id', auth()->id())
                        ->get();
        return view('front.profile.order')->with('orders', $orders);
    }
    

    public function save(Request $request)
    {
        $total = Cart::subtotal(0, '', ''); 
        Order::SaveOrderToData($total);
        Cart::destroy();
        return redirect('/');
    }

    protected function payment(Request $request)
    {
        $nowTime = date("Y-m-d H:i:s");
        $payCart = Cart::instance('shopping')->content();
        $sub = Cart::instance('shopping')->subtotal();


        $appId = '201711021546101248';
        $appKey = '5dbcfc4b930693b37dca2bbd1bb8c19ef530b6d7';
        $params =   [
            'app_id'        =>  $appId,
            'method'        =>  'wxpay.pay.unifiedorder',
            'format'        =>  'json', // 可选
            'charset'       =>  'utf-8', // 可选
            'sign_type'     =>  'md5', // 可选
            'timestamp'     =>  date('Y-m-d H:i:s'),
            'version'       =>  1 // 可选
        ];
         $params['biz_content'] = json_encode(array(
            'out_trade_no' => time(),
            'total_amount' => 0.1,
            'subject' => 'shopping-'.$nowTime, 
            'notify_url' => 'http://easyshop.dev/save/order',
            'return_url' => 'http://easyshop.dev/pay/order?status=0'
        ));
        $sign = static::sign($params,$appKey);
        $params['sign'] = $sign; 
       
        $res = json_decode(static::http($params),true);
 
        // dd($res);
        return view('front.pay.modal',compact('nowTime','payCart','sub','res'));
    }

    /**
     * Http请求
     * @param  array $params 请求参数
     * @return json         返回数据
     */
    public static function http($params = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.fakajun.com/gateway.do');
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        $res = curl_exec($ch);
        return $res;
    }

    public static function sign($params, $app_key)
    {
        $para_filter = array();
        while (list ($key, $val) = each ($params)) {
            if($key == "sign" || $key == "sign_type" || $val == "")continue;
            else    $para_filter[$key] = $params[$key];
        }

        ksort($para_filter);
        reset($para_filter);

        $arg  = "";

        while (list ($key, $val) = each ($para_filter)) {
            // 不是数组的时候才会组合，否则传入数组会出错
            if (!is_array($val)) {
                $arg.=$key."=".$val."&";
            }
        }

        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);
        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){
            $arg = stripslashes($arg);
        }

        $string = $arg . $app_key;

        // md5签名
        return strtoupper(md5($string));
    }
}
